package com.example.fourinarow;

import java.util.LinkedList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

	private static final String TABLE_STATISTICS = "statistics";

	private static final String KEY_ID = "id";
	private static final String KEY_NAME = "Name";
	private static final String KEY_COUNT = "Count";

	private static final int DATABASE_VERSION = 1;

	private static final String DATABASE_NAME = "StatisticDB";

	public MySQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		String CREATE_STATISTIC_TABLE = "CREATE TABLE statistics ( "
				+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT, "
				+ "count INTEGER )";

		db.execSQL(CREATE_STATISTIC_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		db.execSQL("DROP TABLE IF EXISTS statistics");

		this.onCreate(db);
	}


	public void addStatistic(Statistic s) {
		Log.d("addStatistic", s.toString());

		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_NAME, s.getName());
		values.put(KEY_COUNT, s.getCount());
		db.insert(TABLE_STATISTICS, null, values);
		db.close();
	}

	public List<Statistic> getAllStatistics() {
		List<Statistic> statistic = new LinkedList<Statistic>();

		String query = "SELECT  * FROM " + TABLE_STATISTICS;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(query, null);

		Statistic stat = null;
		if (cursor.moveToFirst()) {
			do {
				stat = new Statistic();
				stat.setId(Integer.parseInt(cursor.getString(0)));
				stat.setName(cursor.getString(1));
				stat.setCount(cursor.getInt(2));

				statistic.add(stat);
			} while (cursor.moveToNext());
		}
		db.close();
		return statistic;
	}

	public int updateStatistic(Statistic statistic) {

		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put("name", statistic.getName());
		values.put("count", statistic.getCount());

		int i = db.update(TABLE_STATISTICS, values, KEY_ID + " = ?",
				new String[] { String.valueOf(statistic.getId()) });

		db.close();

		return i;

	}

	public void deleteStatistics(Statistic stat) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TABLE_STATISTICS, KEY_ID + " = ?",
				new String[] { String.valueOf(stat.getId()) });
		db.close();
	}

}
